import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import type { PayloadAction } from '@reduxjs/toolkit'
import type { RootState } from '../../app/store'

// state类型
interface CounterState {
  count: number
}

// 初始state
const initialState: CounterState = {
  count: 1,
}

// 创建异步action creator   过1S才增加
export const incrementAsync = createAsyncThunk(
  'counter/incrementAsync', // action的type
  (num: number) => {
    return new Promise<number>((resolve) => {  // Promise<T> T是成功的value的类型
      setTimeout(() => {
        resolve(num) // 成功的value就会传递给action对象payload
      }, 1000);
    })
  }
)


// 创建当前redux模块管理对象slice
export const counterSlice = createSlice({
  name: 'counter', // 标识名称  => 用来组成action对象的type
  initialState, // 初始状态值
  reducers: { // 当前redux模块的reducer
    // type为 counter/increment
    increment: (state, action: PayloadAction<number>) => {  // {type: 'xxx', payload: num}
      state.count += action.payload
    },
    // type为 counter/decrement
    decrement: (state, action: PayloadAction<number>) => {
      state.count -= action.payload
    },
  },
  // 异步action对应的reducer
  extraReducers: (builder) => {
    // 异步成功的reducer处理
    builder.addCase(incrementAsync.fulfilled, (state, action) => {
      state.count += action.payload
    })
  },
})

// 得到内部自动生成的action creator
export const { increment, decrement } = counterSlice.actions

// 得到内部自动生成的reducer函数
export const counterReducer =  counterSlice.reducer

// 读取当前count状态数据的select函数
export const selectCount = (state: RootState) => state.counter.count

